package com.example.emojibase.view;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.emojibase.AuthApiService;
import com.example.emojibase.R;
import com.example.emojibase.pojo.Reply;
import com.example.emojibase.pojo.User;
import com.example.emojibase.RetrofitClient;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Login extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        AuthApiService service = RetrofitClient.getClient().create(AuthApiService.class);
        EditText userid=findViewById(R.id.userid);
        EditText password=findViewById(R.id.password);
        Button button1=findViewById(R.id.button1);
        Button button2=findViewById(R.id.button2);
        button1.setOnClickListener(view -> {
            User user=new User(userid.getText().toString(),password.getText().toString());
            service.login(user).enqueue(new Callback<Reply>() {
                @Override
                public void onResponse(@NonNull Call<Reply> call, @NonNull Response<Reply> response) {
                    if (response.isSuccessful()) {
                        assert response.body() != null;
                        Reply reply=response.body();
                        if (reply.getStatus()==1){
                            EmojiShow.isLogin=true;
                            Intent intent = new Intent(Login.this, EmojiShowOnline.class);
                            startActivity(intent);
                        }
                        else {
                            System.out.println(reply.getMessage());
                            Toast.makeText(Login.this, reply.getMessage(), Toast.LENGTH_SHORT).show();
                            // 处理成功的响应
                        }
                    } else {
                        // 处理错误响应
                        Toast.makeText(Login.this, "Response failed", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(@NonNull Call<Reply> call, @NonNull Throwable t) {
                    Log.i("TAG", ""+t);
                    // 处理请求失败
                    Toast.makeText(Login.this, "Get response failed", Toast.LENGTH_SHORT).show();
                }
            });
        });
        button2.setOnClickListener(view -> {
            Intent intent = new Intent(Login.this, Register.class);
            startActivity(intent);
        });
    }

}
